package com.edgclub.edg.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.edgclub.edg.Constant;
import com.edgclub.edg.GuZhiApplication;
import com.edgclub.edg.R;
import com.edgclub.edg.api.FriendApi;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.fragment.BBHomeFragment;
import com.edgclub.edg.fragment.EDGHomeFragment;
import com.edgclub.edg.fragment.FindHomeFragment;
import com.edgclub.edg.fragment.MessageFragment;
import com.edgclub.edg.fragment.YouZanWebFragment;
import com.edgclub.edg.huanxin.DemoHelper;
import com.edgclub.edg.task.UpdateManager;
import com.edgclub.edg.uc.DeleteDialog;
import com.edgclub.edg.uc.UpdateDialog;
import com.edgclub.edg.utils.util.CommAppPrefUtils;
import com.edgclub.edg.utils.util.DateUtils;
import com.edgclub.edg.utils.util.StringUtils;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.rockerhieu.emojicon.emoji.SerializeManager;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;
import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class GzMainActivity extends GzBaseTooolBarActivity implements View.OnClickListener {

    private RelativeLayout mFragment_container;
    private RadioButton mTab_first;
    private RadioButton mTab_second;
    private RadioButton mTab_three;
    private RadioButton mTab_four;
    private RadioButton mTab_edg;
    private RadioButton tab_edgdef;
    private RadioGroup mTab_group;
    private TextView unreadLabel;


    private FragmentManager mFragmentManager;// Fragment管理�
    private FragmentTransaction mFragmentTransaction;
    private String mCurrentFragmentTag = "";// 当前fragment标签

    // 账号在别处登录
    public boolean isConflict = false;
    // 账号被移除
    private boolean isCurrentAccountRemoved = false;

    private List<String> disturbList;
    private FriendApi friendApi;

    private SQLiteDatabase db;

    private EditText editText;

    private UserPrefUtils userPrefUtils;
    private final String mServiceName = "com.pplive.sdk.service";

    private CommAppPrefUtils appPrefUtils;

    @Override
    public int getContentView() {
        return R.layout.activity_main;
    }

    @Override
    public void setTitleBarView() {

    }

    /**
     * 初始化界面
     */
    @Override
    public void initView() {
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).register(this);
        UmengUpdateAgent.update(this);
//        GuZhiApplication.getInstance().setSys_admin();
        userPrefUtils = new UserPrefUtils(this);
        friendApi = new FriendApi(this);
        mFragmentManager = getSupportFragmentManager();


        disturbList = (List<String>) SerializeManager.loadFile(Constant.notDisturb + GuZhiApplication.getInstance().getUserId() + "");
        if (null == disturbList)
            disturbList = new ArrayList<>();
        mFragment_container = (RelativeLayout) findViewById(R.id.fragment_container);
        mTab_first = (RadioButton) findViewById(R.id.tab_first);
        mTab_second = (RadioButton) findViewById(R.id.tab_second);
        mTab_three = (RadioButton) findViewById(R.id.tab_three);
        mTab_four = (RadioButton) findViewById(R.id.tab_four);
        mTab_edg = (RadioButton) findViewById(R.id.tab_edg);
        tab_edgdef = (RadioButton) findViewById(R.id.tab_edgdef);
        mTab_group = (RadioGroup) findViewById(R.id.tab_group);
        unreadLabel = (TextView) findViewById(R.id.unreadLabel);

        mTab_edg.setOnClickListener(this);
        mTab_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                mTab_edg.setChecked(false);
                switch (i) {
                    case R.id.tab_first:
                        setStatusBarHeight(true);
                        switchFragmen("BB");
                        MobclickAgent.onEvent(GzMainActivity.this, "EC_TAB_BB");
                        break;
                    case R.id.tab_second:
                        setStatusBarHeight(true);
                        switchFragmen("发现");
                        MobclickAgent.onEvent(GzMainActivity.this, "EC_TAB_FIND");
                        break;
                    case R.id.tab_three:
                        setStatusBarHeight(true);
                        switchFragmen("消息");
                        unreadLabel.setVisibility(View.INVISIBLE);
                        ((MessageFragment) getFragment(mCurrentFragmentTag)).refreshChatList("", 0);
                        MobclickAgent.onEvent(GzMainActivity.this, "EC_TAB_MESSAGE");
                        break;
                    case R.id.tab_four:
                        setStatusBarHeight(true);
                        switchFragmen("我的");
                        MobclickAgent.onEvent(GzMainActivity.this, "EC_TAB_STORE");
                        break;
                    default:
                        setStatusBarHeight(true);
                        tab_edgdef.setChecked(true);

                        break;

                }
            }
        });


        appPrefUtils = new CommAppPrefUtils(this);
        long time = appPrefUtils.getNextUpdateTime();
        if(appPrefUtils.isDown() && !DateUtils.isSameDay(time) && GuZhiApplication.getInstance().getAppInfo() != null){
            final UpdateDialog dialog = UpdateDialog.create(this, true);
            dialog.show();
            dialog.setCancelable(true);
            dialog.setTitle("发现新版本");
            dialog.setContent(GuZhiApplication.getInstance().getAppInfo().getRemark());
            dialog.setSubmittext("立即更新");
            dialog.setCancle("以后再说");
            dialog.setTvOkColor(getResources().getColor(R.color.c1));
            dialog.setCancelListener(new UpdateDialog.CancelClickListener() {

                @Override
                public void cancelClick() {
                    dialog.dismiss();
                    appPrefUtils.saveNextUpdateTime(System.currentTimeMillis());
                }
            });
            dialog.setSubmitListener(new UpdateDialog.SubmitClickListener() {

                @Override
                public void submitClick() {
                    dialog.dismiss();
                    UpdateManager updateManager = new UpdateManager(GzMainActivity.this , GuZhiApplication.getInstance().getAppInfo());
                    updateManager.installApk();
                }
            });
        }
    }


    @Override
    public void initData() {
        if (Constant.MiPush_Type_Reply == getIntent().getIntExtra("MiPushu_Type", 0)) {
            mTab_three.setChecked(true);
            mTab_edg.setChecked(false);
            setStatusBarHeight(false);
            switchFragmen("消息");
            GuZhiApplication.getInstance().isFirstNew = true;
        } else if (Constant.MiPush_Type_Report == getIntent().getIntExtra("MiPushu_Type", 0)) {
            mTab_three.setChecked(true);
            mTab_edg.setChecked(false);
            setStatusBarHeight(false);
            switchFragmen("消息");
            GuZhiApplication.getInstance().isReportNew = true;
        } else if (Constant.MiPush_Type_Focus == getIntent().getIntExtra("MiPushu_Type", 0)) {
            Intent intent2 = new Intent(GzMainActivity.this, GzTopicDetailActivity.class);
            intent2.putExtra("topicId", getIntent().getStringExtra("postId"));
            intent2.putExtra("MiPushu_Type", Constant.MiPush_Type_Focus);
            intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent2);

        } else {
            setStatusBarHeight(true);
            switchFragmen("BB");
        }
        //注册local广播接收者，用于接收demohelper中发出的群组联系人的变动通知
        registerBroadcastReceiver();
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tab_edg:
                mTab_first.setChecked(false);
                mTab_second.setChecked(false);
                mTab_three.setChecked(false);
                mTab_four.setChecked(false);
                tab_edgdef.setChecked(true);
                mTab_edg.setChecked(true);
                switchFragmen(getString(R.string.tab_home));
                setStatusBarHeight(true);
                MobclickAgent.onEvent(GzMainActivity.this, "EC_TAB_EDG");
                break;
        }
    }

    /**
     * 点击不同的Tab切换fragment
     *
     * @param tag
     */
    private void switchFragmen(String tag) {
        try {
            if (TextUtils.equals(mCurrentFragmentTag, tag))
                return;
            if (mCurrentFragmentTag != null)
                detachFragment(getFragment(mCurrentFragmentTag));
            attachFragment(R.id.fragment_container, getFragment(tag), tag);
            mCurrentFragmentTag = tag;
            commitTransactions();
        } catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 初始化FragmentTransaction
     *
     * @return FragmentTransaction实例
     */
    protected FragmentTransaction ensureTransaction() {
        if (mFragmentTransaction == null) {
            mFragmentTransaction = mFragmentManager.beginTransaction();
            mFragmentTransaction
                    .setTransition(FragmentTransaction.TRANSIT_NONE);
        }
        return mFragmentTransaction;
    }

    /**
     * 将对应的fragment添加到容器中
     *
     * @param layout 父容器
     * @param f      fragment实例
     * @param tag    标签
     */
    protected void attachFragment(int layout, Fragment f, String tag) {
        if (f != null) {
            if (f.isHidden()) {// 如果当前fragment只是隐藏，则显示出来
                ensureTransaction();
                mFragmentTransaction.show(f);
            } else if (!f.isAdded()) {// 如果当前fragment没有添加到容器中，则先要添加到容器中
                ensureTransaction();
                mFragmentTransaction.add(layout, f, tag);
            }
        }
    }

    /**
     * 将对应fragment隐藏
     *
     * @param f 需要隐藏的fragment
     */
    protected void detachFragment(Fragment f) {
        if (f != null && !f.isDetached()) {
            ensureTransaction();
            mFragmentTransaction.hide(f);
        }
    }

    /**
     * 保存fragment状态，添加或隐藏fragment最后都需要调用此函数
     */
    protected void commitTransactions() {
        if (mFragmentTransaction != null && !mFragmentTransaction.isEmpty()) {
            mFragmentTransaction.commitAllowingStateLoss();
            mFragmentTransaction = null;
        }
    }

    /**
     * 根据tag获取对应的Fragment
     *
     * @param tag 标签
     * @return 对应tag的Fragment实例
     */
    private Fragment getFragment(String tag) {
        Fragment f = mFragmentManager.findFragmentByTag(tag);
        if (f == null) {
            // 在这里判断tag,不同则实例化对应的fragment，
            if (getString(R.string.tab_bb).equals(tag)) {
                f = BBHomeFragment.newInstance(tag);
            } else if (getString(R.string.tab_find).equals(tag)) {
                f = FindHomeFragment.newInstance(tag);
            } else if (getString(R.string.tab_near).equals(tag)) {
                f = MessageFragment.newInstance(tag);
            } else if (getString(R.string.tab_chat).equals(tag)) {
                f = YouZanWebFragment.newInstance(tag);
            } else if (getString(R.string.tab_home).equals(tag)) {
                f = EDGHomeFragment.newInstance(tag);
            }
        }

        return f;
    }


    EMMessageListener messageListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            // 提示新消息
            for (EMMessage message : messages) {
                String strUser = message.getUserName();
                int t = 0;
                if (message.getChatType() == EMMessage.ChatType.GroupChat || message.getChatType() == EMMessage.ChatType.ChatRoom) {
                    strUser = message.getTo();
                    t = 2;
                } else {
                    // 单聊消息
                    t = 1;
                    strUser = message.getFrom();
                }
                if (!disturbList.contains(strUser))
                    DemoHelper.getInstance().getNotifier().onNewMsg(message);
                refreshUIWithMessage(strUser, t);
            }
//            updateChat(messages);
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            int messPostNum = userPrefUtils.getMessNum();
            int messReportNum = userPrefUtils.getReportNum();
            for (EMMessage message : messages) {
                EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) message.getBody();
                final String action = cmdMsgBody.action();//获取自定义action
                if ("posts_reply".equals(action)) {
                    messPostNum++;
                    userPrefUtils.saveMessTip(true);
                    userPrefUtils.setMessNum(messPostNum);
                }
                if ("report_msg".equals(action)) {
                    messReportNum++;
                    userPrefUtils.saveReportTip(true);
                    userPrefUtils.setReportNum(messReportNum);
                }
            }
            if (messPostNum > 0) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!"消息".equals(mCurrentFragmentTag)) {
                            updateUnreadLabel();
                        } else
                            ((MessageFragment) getFragment(mCurrentFragmentTag)).refreshReplyList();

                    }
                });
            }
            if (messReportNum > 0) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!"消息".equals(mCurrentFragmentTag)) {
                            updateUnreadLabel();
                        } else
                            ((MessageFragment) getFragment(mCurrentFragmentTag)).refreshReportList();

                    }
                });
            }

        }

        @Override
        public void onMessageRead(List<EMMessage> list) {

        }

        @Override
        public void onMessageDelivered(List<EMMessage> list) {

        }


        @Override
        public void onMessageChanged(EMMessage message, Object change) {
        }
    };


    private void refreshUIWithMessage(final String imid, final int type) {

        runOnUiThread(new Runnable() {
            public void run() {
                // 刷新bottom bar消息未读数

                if ("消息".equals(mCurrentFragmentTag)) {
                    // 当前页面如果为聊天历史页面，刷新此页面
//                    if (getFragment(mCurrentFragmentTag) != null) {
                    ((MessageFragment) getFragment(mCurrentFragmentTag)).refreshChatList(imid, type);
//                    }
                }
                updateUnreadLabel();

            }
        });
    }

    private void registerBroadcastReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_CONTACT_CHANAGED);
        intentFilter.addAction(Constant.ACTION_GROUP_CHANAGED);
        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                if ("消息".equals(mCurrentFragmentTag)) {
                    // 当前页面如果为聊天历史页面，刷新此页面
//                    if (getFragment(mCurrentFragmentTag) != null) {
                    ((MessageFragment) getFragment(mCurrentFragmentTag)).refreshChatList("", 0);
//                    }
                }
                updateUnreadLabel();

            }
        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }


    private void unregisterBroadcastReceiver() {
        broadcastManager.unregisterReceiver(broadcastReceiver);
    }

    /**
     * 刷新未读消息数
     */
    public void updateUnreadLabel() {
        int count = getUnreadMsgCountTotal();
        if (count > 0 || userPrefUtils.getMessNum() > 0 || userPrefUtils.getReportNum() > 0) {
            unreadLabel.setVisibility(View.VISIBLE);
        } else {
            unreadLabel.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 获取未读消息数
     *
     * @return
     */
    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        int chatroomUnreadMsgCount = 0;
        unreadMsgCountTotal = EMClient.getInstance().chatManager().getUnreadMsgsCount();
        for (EMConversation conversation : EMClient.getInstance().chatManager().getAllConversations().values()) {
            if (conversation.getType() == EMConversation.EMConversationType.ChatRoom)
                chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount();
        }
        return unreadMsgCountTotal - chatroomUnreadMsgCount;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isConflict && !isCurrentAccountRemoved) {
            updateUnreadLabel();
        }
        // unregister this event listener when this activity enters the
        // background
        DemoHelper sdkHelper = DemoHelper.getInstance();
        sdkHelper.pushActivity(this);

//        EMClient.getInstance().chatManager().addMessageListener(messageListener);


        if ("消息".equals(mCurrentFragmentTag) && null != ((MessageFragment) getFragment(mCurrentFragmentTag)))
            ((MessageFragment) getFragment(mCurrentFragmentTag)).setCurrent(1);

    }

    @Override
    public void onStop() {
//        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
        DemoHelper sdkHelper = DemoHelper.getInstance();
        sdkHelper.popActivity(this);

        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (conflictBuilder != null) {
            conflictBuilder.create().dismiss();
            conflictBuilder = null;
        }
        unregisterBroadcastReceiver();
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).unregister(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getBooleanExtra(Constant.ACCOUNT_CONFLICT, false) && !isConflictDialogShow) {
            showConflictDialog();
        } else if (intent.getBooleanExtra(Constant.ACCOUNT_REMOVED, false) && !isAccountRemovedDialogShow) {
            try {
                showAccountRemovedDialog();
            } catch (Exception e){
                e.printStackTrace();
            }

        }
        if (Constant.MiPush_Type_Reply == intent.getIntExtra("MiPushu_Type", 0)) {
            mTab_three.setChecked(true);
            mTab_edg.setChecked(false);
            setStatusBarHeight(false);
            unreadLabel.setVisibility(View.INVISIBLE);
            GuZhiApplication.getInstance().isFirstNew = true;
            switchFragmen("消息");
        } else if (Constant.MiPush_Type_Report == intent.getIntExtra("MiPushu_Type", 0)) {
            mTab_three.setChecked(true);
            mTab_edg.setChecked(false);
            unreadLabel.setVisibility(View.INVISIBLE);
            GuZhiApplication.getInstance().isReportNew = true;
            switchFragmen("消息");
        } else if (Constant.MiPush_Type_Focus == intent.getIntExtra("MiPushu_Type", 0)) {
            Intent intent2 = new Intent(GzMainActivity.this, GzTopicDetailActivity.class);
            intent2.putExtra("topicId", intent.getStringExtra("postId"));
            intent2.putExtra("MiPushu_Type", Constant.MiPush_Type_Focus);
            intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent2);
        }
    }

    private android.app.AlertDialog.Builder conflictBuilder;
    private android.app.AlertDialog.Builder accountRemovedBuilder;
    private boolean isConflictDialogShow;
    private boolean isAccountRemovedDialogShow;
    private BroadcastReceiver internalDebugReceiver;
    private BroadcastReceiver broadcastReceiver;
    private LocalBroadcastManager broadcastManager;

    /**
     * 显示帐号在别处登录dialog
     */
    private void showConflictDialog() {
        isConflictDialogShow = true;
        DemoHelper.getInstance().logout(false, null);
        String st = getResources().getString(R.string.Logoff_notification);
        if (!GzMainActivity.this.isFinishing()) {
            // clear up global variables
            try {
                if (conflictBuilder == null)
                    conflictBuilder = new android.app.AlertDialog.Builder(GzMainActivity.this);
                conflictBuilder.setTitle(st);
                conflictBuilder.setMessage(R.string.connect_conflict);
                conflictBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        conflictBuilder = null;
                        finish();
                        Intent intent = new Intent(GzMainActivity.this, GzLoginActivity.class);
                        intent.putExtra("remember_phone", userPrefUtils.getUser().getPhone());
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                });
                conflictBuilder.setCancelable(false);
                conflictBuilder.create().show();
                isConflict = true;
            } catch (Exception e) {
            }

        }

    }

    /**
     * 帐号被移除的dialog
     */
    private void showAccountRemovedDialog() {
        isAccountRemovedDialogShow = true;
        DemoHelper.getInstance().logout(false, null);
        String st5 = getResources().getString(R.string.Remove_the_notification);
        if (!GzMainActivity.this.isFinishing()) {
            // clear up global variables
            try {
                if (accountRemovedBuilder == null)
                    accountRemovedBuilder = new android.app.AlertDialog.Builder(GzMainActivity.this);
                accountRemovedBuilder.setTitle(st5);
                accountRemovedBuilder.setMessage("此用户已被移除");
                accountRemovedBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        accountRemovedBuilder = null;
                        finish();
                        startActivity(new Intent(GzMainActivity.this, GzLoginActivity.class));
                    }
                });
                accountRemovedBuilder.setCancelable(false);
                accountRemovedBuilder.create().show();
                isCurrentAccountRemoved = true;
            } catch (Exception e) {
            }

        }

    }


    /**
     * 内部测试代码，开发者请忽略
     */
    private void registerInternalDebugReceiver() {
        internalDebugReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                DemoHelper.getInstance().logout(false, new EMCallBack() {

                    @Override
                    public void onSuccess() {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                // 重新显示登陆页面
                                finish();
                                startActivity(new Intent(GzMainActivity.this, GzLoginActivity.class));

                            }
                        });
                    }

                    @Override
                    public void onProgress(int progress, String status) {
                    }

                    @Override
                    public void onError(int code, String message) {
                    }
                });
            }
        };
        IntentFilter filter = new IntentFilter(getPackageName() + ".em_internal_debug");
        registerReceiver(internalDebugReceiver, filter);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        //getMenuInflater().inflate(R.menu.context_tab_contact, menu);
    }

    @Subscribe
    public void refreshDisturb(HashMap<String, Object> map) {
        String event = (String) map.get("event");
        if (null != event && BroadCastEvent.CHATLIST_DISTURB.equals(event)) {
            disturbList = (List<String>) SerializeManager.loadFile(Constant.notDisturb + GuZhiApplication.getInstance().getUserId() + "");
            if (null == disturbList)
                disturbList = new ArrayList<>();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mCurrentFragmentTag.equals(getString(R.string.tab_chat))) {
                if (((YouZanWebFragment) getFragment(mCurrentFragmentTag)).onKeyDown(keyCode, event)){

                } else {
                    moveTaskToBack(false);
                }
            } else
            moveTaskToBack(false);
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }

    // 跳转发现
    @Subscribe
    public void updateUserFindEvent(HashMap<String, Object> map) {
        String event = (String) map.get("event");
        if (BroadCastEvent.USERFIND.equals(event)) {
            mTab_first.setChecked(false);
            mTab_second.setChecked(true);
            setStatusBarHeight(true);
            switchFragmen("发现");
            MobclickAgent.onEvent(GzMainActivity.this, "EC_TAB_FIND");
        }
    }

    // 跳转商城
    @Subscribe
    public void jumptaobaoEvent(HashMap<String, Object> map) {
        String event = (String) map.get("event");
        if (BroadCastEvent.JUMPTAOBAO.equals(event)) {
            mTab_first.setChecked(false);
            mTab_four.setChecked(true);
            setStatusBarHeight(true);
            switchFragmen("我的");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (mCurrentFragmentTag.equals(getString(R.string.tab_chat))) {
            ((YouZanWebFragment) getFragment(mCurrentFragmentTag)).onActivityResult(requestCode, resultCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (mCurrentFragmentTag.equals(getString(R.string.tab_chat))) {
            if(((YouZanWebFragment) getFragment(mCurrentFragmentTag)).onBackPressed()){

            } else {
                moveTaskToBack(false);
            }

        }
    }
}